package com.ppm.common.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ppm.common.base.dto.ResultDTO;
import com.ppm.common.base.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author: qinhui
 * @date: 2020/7/2 9:09
 */
@Component
public class RestTemplateUtils {
    private static final String SUCCESS = "200";
    private static final String KEY_CODE = "code";
    private static final String KEY_MSG = "msg";

    public JSONObject Rpc(String url, MultiValueMap<String, String> multiValueMap, RestTemplate restTemplate) {

        JSONObject jsonObject = goPost(url, multiValueMap, restTemplate);
        System.out.println(jsonObject.toJSONString());
        if (!SUCCESS.equals(jsonObject.getString(KEY_CODE))) {
            throw new BaseException(Integer.parseInt(jsonObject.getString(KEY_CODE)), jsonObject.getString(KEY_MSG));
        }
        return jsonObject;

    }

    public  JSONObject goPost(String url, MultiValueMap<String, String> data, RestTemplate restTemplate) {
        JSONObject json;
        if(restTemplate==null){
            System.out.println("restTemplate is null");
        }
        try {
            System.out.println("post接口入参地址："+url);
            System.out.println("post接口入参参数："+ JSON.toJSONString(data));
            json = restTemplate.postForObject(url, data, JSONObject.class);
            System.out.println("post接口返回参数信息："+ JSON.toJSONString(json));
            if(json == null) {
                throw new BaseException(500, "系统繁忙");
            }
        } catch (Exception e) {
            System.out.println("请求得数据："+data.toString());
            e.printStackTrace();
            throw new BaseException(500, "系统繁忙");
        }
        return json;
    }

}
